package com.chrudgames.stayintouch;


import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

public class Setup extends Activity implements OnClickListener {
	
	public String phoneNumbers = "";
	public String phoneNumbers2 = "";
	
	 String DurationPreference = "";
    
	class CCall implements Comparable<CCall> { 
	    Long cDate; 
		String cNumber;
	    int cType;
	    int cDuration;
	    CCall( Long d, String s, int i, int ii ) { 
	        cDate = d;
	    	cNumber = s;
	        cType = i;
	        cDuration = ii;
	    }

	    public int compareTo(CCall two ) {

	        return two.cDate.compareTo( this.cDate );
	   }
	   public String toString(){
	       return "CCall[cDate="+cDate+", cNumber="+cNumber+"]";
	   }
	}


	public ArrayList<CCall> arrCall = new ArrayList<CCall>();
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setup);
        
         
     getInfo();
     getCalls();
     getSMS();
     getTotals();
       
      
    
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.options:
            	Intent i = new Intent(this, Prefs.class);
               	startActivity(i);
    	
                return true;
            case R.id.upgrade:
            	Intent i3 = new Intent(this, Upgrade.class);
               	startActivity(i3);
                return true;
            case R.id.help:
            	Intent i2 = new Intent(this, Help.class);
               	startActivity(i2);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
	@Override
	public void onClick(View v) {
		
switch (v.getId()) {
    	
    	case R.id.btnSave:
    		 DatabaseHandler db = new DatabaseHandler(this);
    		 
    		 Bundle b = getIntent().getExtras();
    	     String lookupKey = b.getString("lookupKey");
    	     
    	     EditText myText = (EditText) this.findViewById(R.id.txtMax2);

    		 
    	     db.runQuery("update contacts set frequency = " + myText.getText().toString() + " where _id='" + lookupKey.toString() + "'");
    	     db.close();
    		
    		
    		finish();
          	break;
		}
		
	}
	
	public void getInfo(){
    	

        SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getBaseContext());
		
        DurationPreference = prefs.getString("pref_duration", "60");
        if(DurationPreference.length()<1){DurationPreference="0";}
        
        Bundle b = getIntent().getExtras();
        String lookupKey = b.getString("lookupKey");
    	String tmpPhone = "";
        
              
    	Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
    	
    	
    	Cursor c = getContentResolver().query(lookupUri, new String[]{Contacts.DISPLAY_NAME, Contacts.LAST_TIME_CONTACTED, Contacts.HAS_PHONE_NUMBER},null, null, null);
    	try {
    	    c.moveToFirst();
    	    String displayName = c.getString(0);
                       
    	    
            String hasPhone = c.getString(2);

        
           if (hasPhone.contains("1")) { 
        	   
     	    	Log.d("Number",lookupKey);
    	    	  
        	   
            Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY +" = '" + lookupKey + "'", null, null);  
      	      while (phones.moveToNext()) { 
      	    	  
      	    	tmpPhone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));  
      	    	tmpPhone = tmpPhone.replaceAll("[^0-9]","");
      	    	
      	   
      	    	
      	    	if(tmpPhone.length()>6){tmpPhone = tmpPhone.substring(tmpPhone.length() - 6);}
      	    	
      	    	phoneNumbers = phoneNumbers + "'" + tmpPhone + "',";
      	    	
      	    	
      	        phoneNumbers2 = phoneNumbers2 + phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) + ", ";

    
      	        
      	      
      	      } 
      	   phones.close(); 
      	   
      	 if(phoneNumbers.length()>1){  phoneNumbers = phoneNumbers.substring(0, phoneNumbers.length() - 1);}
      	if(phoneNumbers2.length()>2){phoneNumbers2 = phoneNumbers2.substring(0, phoneNumbers2.length() - 2);}
      	//phoneNumbers = phoneNumbers.replaceAll("[^0-9]","");

      	 TextView mTextView = (TextView) findViewById(R.id.tvInfo);
         mTextView.setText(this.getString(R.string.StayInTouch_found) + displayName.toString() + ": " + phoneNumbers2 );
         
      	}
            
            
    	} finally {
    	    
    	}
    	
    	c.close();
    }

	public void getTotals(){
		
		Collections.sort(arrCall);
		
		
		Long datOldest = null;
		Long datLatest = null;
		Long interval = null;
		Long maxInterval = null;

        
       if (arrCall.size() > 0)  {

    	   datLatest = arrCall.get(0).cDate;
    	   
    	   for(int i=0;i<arrCall.size();i++)
	    	{

       		   
        	  
        	   if(datOldest!=null){
    		   
        		   interval = datOldest - arrCall.get(i).cDate;
                   
        		   if(maxInterval==null)maxInterval = interval;
        		   if(interval>maxInterval)maxInterval = interval;
               
    		   }
               
        		   datOldest = arrCall.get(i).cDate;
        		   
           };

            TextView mTextView = (TextView) findViewById(R.id.tvInfo2);
            mTextView.setText(this.getString(R.string.According_to) + "\u0020" + (TimeUnit.MILLISECONDS.toSeconds((datLatest - datOldest)/(arrCall.size()))/60/60/24 + 1)  + "\u0020" + this.getString(R.string.The_longest)
            		 + "\u0020"+ +  TimeUnit.MILLISECONDS.toSeconds(maxInterval)/60/60/24  + "\u0020" +  this.getString(R.string.days2));
      
           
           }else{
           
        	   TextView mTextView = (TextView) findViewById(R.id.tvInfo2);
               mTextView.setText(this.getString(R.string.There_are_no));
           
           }
  		       		        
    
	}	
	 public void getCalls(){
	    	
	    	
		    
	    	final String[] projection = null;
	    	final String selection = "duration>" + DurationPreference + " and substr(replace(number, '-',''),-6,6) IN (" + phoneNumbers + ")";
	    	final String selectionArgs[] = null;// phoneNumbers;
	    	final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
	    	Cursor c = null;
	    	
	 
	    	//try{
	    	  
	        
	           c = getContentResolver().query(
	    	            Uri.parse("content://call_log/calls"),
	    	            projection,
	    	            selection,
	    	            selectionArgs,
	    	            sortOrder);
	           
	
	            
		           if (c.moveToFirst()) {
			              
		        	//   datLatest = c.getLong(0);
		        	   
		        	   do {
		                   
		        		  
		       		CCall call = new CCall(c.getLong(c.getColumnIndex("date")),c.getString(c.getColumnIndex("number")),c.getInt(c.getColumnIndex("type")),c.getInt(c.getColumnIndex("duration")));
		        		
		        	arrCall.add(call);
		        		
		        		  // Log.w("SIT", c.getCount() + "");  
		        		 //Log.w("SIT",android.text.format.DateFormat.getTimeFormat(context).format(new Date(c.getLong(c.getColumnIndex("date")))));
		                   
		        		   
		                   
		               } while (c.moveToNext()); 
	            
	    		
	    	}
		         
		           
		  
			                      
		       		        
	    	//}catch(Exception ex){
	    	//	Log.w("SIT",ex.getMessage().toString());
	    	//}finally{
	    	   c.close();
	    	//}
	    	
	    	   
	    }
	    
	    public void getSMS(){
	    	
	    	
		    
	    	final String[] projection = null;
	    	final String selection = "substr(replace(address, '-',''),-6,6) IN (" + phoneNumbers + ")";//  "person='" + lookupKey +"'";
	    	final String selectionArgs[] = null;// phoneNumbers;
	    	final String sortOrder = null;
	    	Cursor c = null;
	    	
	    	
	    	//try{
	    	  
	        
	           c = getContentResolver().query(
	    	            Uri.parse("content://sms/sent"),
	    	            projection,
	    	            selection,
	    	            selectionArgs,
	    	            sortOrder);
	           
	
	            
		           if (c.moveToFirst()) {
			              
		        	//   datLatest = c.getLong(0);
		        	   
		        	   do {
		                   
		        		  
		        		CCall call = new CCall(c.getLong(c.getColumnIndex("date")),c.getString(c.getColumnIndex("address")),4,0);
		        		
		        		arrCall.add(call);
		        		
		        		  // Log.w("SIT", c.getCount() + "");  
		        		 //Log.w("SIT",android.text.format.DateFormat.getTimeFormat(context).format(new Date(c.getLong(c.getColumnIndex("date")))));
		                   
		        		   
		                   
		               } while (c.moveToNext()); 
	            
	    		
	    	}
		         
		           
		           c = getContentResolver().query(
		    	            Uri.parse("content://sms/inbox"),
		    	            projection,
		    	            selection,
		    	            selectionArgs,
		    	            sortOrder);
		           
		
		            
			           if (c.moveToFirst()) {
				              
			        	//   datLatest = c.getLong(0);
			        	   
			        	   do {
			                   
			        		 
			        		   CCall call = new CCall(c.getLong(c.getColumnIndex("date")),c.getString(c.getColumnIndex("address")),5,0);
				        		
				        		arrCall.add(call);
			        		
			                   
			               } while (c.moveToNext()); 
		            
		    		
		    	}
			                      
		       		        
	    	//}catch(Exception ex){
	    	//	Log.w("SIT",ex.getMessage().toString());
	    	//}finally{
	    	   c.close();
	    	//}
	    	
	    	   
	    }
}